import Vue from 'vue'
import Vuex from 'vuex'
import { setToken, getToken, removeToken } from '@/utils/set-token'
import { login } from '@/api/loginmoduls'

// import Cookies from 'js-cookie'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    token: getToken(),
    name: '',
    avatar: '',
    introduction: '',
    roles: []
  },
  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    }
  },
  actions: {
    login ({ commit }, userInfo) {
      const { username, password } = userInfo
      return new Promise((resolve, reject) => {
        login({ username: username.trim(), password: password }).then(response => { // 这里处理过数据之后传参
          const { data } = response
          // commit('SET_TOKEN', data.token)
          // setToken(data.token)// 设置token
          // resolve()
          var arry = data.split('|')
          if (arry[0] === undefined || arry[0] === '') {
            // reject()
          } else {
            commit('SET_TOKEN', arry[0])
            setToken(arry[0])
            resolve()
          }
        }).catch(error => {
          reject(error)
          console.log(error)
        })
      })
    },
    // logout ({ commit, state }) {
    //   return new Promise((resolve, reject) => {
    //     logout(state.token).then(() => {
    //       commit('SET_TOKEN', ' ')
    //       removeToken()
    //       // resetRouter()
    //       resolve()
    //     }).catch(error => {
    //       reject(error)
    //     })
    //   })
    // },
    logout ({ commit, state }) {
      commit('SET_TOKEN', ' ')
      removeToken()
      // resetRouter()
    },
    resetToken ({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      })
    }
  },
  getters: {
    token: state => state.token,
    roles: state => state.roles
  },
  modules: {
  }
})
